package com.moyun.zbmy.zizhou.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Cache;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.base.BaseAccountActivity;
import com.moyun.zbmy.zizhou.beans.AccountBean;
import com.moyun.zbmy.zizhou.beans.AccountTabBean;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.AccountDetailPagerAdapter;
import com.moyun.zbmy.zizhou.ui.fragment.AccountDetailNewsFragment;
import com.moyun.zbmy.zizhou.ui.utils.DataUtils;
import com.moyun.zbmy.zizhou.ui.utils.GlideCircleTransform;
import com.moyun.zbmy.zizhou.ui.utils.GlideUtil;
import com.moyun.zbmy.zizhou.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 公众号详情页
 */
public class AccountDetailActivity extends BaseAccountActivity implements OnTabSelectListener {

    @BindView(R.id.account_top_name)
    protected CustomFontTextView accountTopName;


    @BindView(R.id.account_avatar)
    protected ImageView accountAvatar;
    @BindView(R.id.account_subscribe)
    protected ImageView accountSubscribe;

    @BindView(R.id.account_publish_num)
    protected CustomFontTextView accountPublishNum;//头条数
    @BindView(R.id.account_attention_num)
    protected CustomFontTextView accountAttentionNum;//关注数
    @BindView(R.id.account_fans_num)
    protected CustomFontTextView accountFansNum;//粉丝数
    @BindView(R.id.account_be_praised_num)
    protected CustomFontTextView accountBePraisedNum;//获赞数

    @BindView(R.id.account_aut_info)
    protected CustomFontTextView accountAutInfo;//认证
    @BindView(R.id.account_address)
    protected CustomFontTextView accountAddress;//位置
    @BindView(R.id.account_introduction)
    protected CustomFontTextView accountIntro;//简介


    @BindView(R.id.account_tablay)
    protected SlidingTabLayout accountTabLay;
    @BindView(R.id.account_content_vp)
    protected ViewPager accountContentVp;
    private Handler handler;
    private boolean mIsLoading = false;
    public static final String ACCOUNT_IS_SELF = "is_self_account";
    public static final String ACCOUNT_ID = "account_id";
    public static final String ACCOUNT_AVATAR = "account_avatar";
    private AccountBean mAccountDetailBean;
    private GlideCircleTransform circleTransform;
    private AccountDetailPagerAdapter adapter;
    private boolean isSelfAccount = false;
    private String accointId = "";
    private String accountAvatarUrl = "";
    private int currentIndex = 0;
    //页面滑动位移
    private int currentOffset = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();
        isSelfAccount = getIntent().getBooleanExtra(ACCOUNT_IS_SELF, false);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_account_detail);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        accointId = getIntent().getStringExtra(ACCOUNT_ID);
        accountAvatarUrl = getIntent().getStringExtra(ACCOUNT_AVATAR);
        circleTransform = new GlideCircleTransform(this);
        if (isSelfAccount) {
            accountSubscribe.setVisibility(View.GONE);
        } else {
            accountSubscribe.setVisibility(View.VISIBLE);
        }
        getAccountDetail();

    }


    /**
     * 请求公众号详情数据
     */
    private void getAccountDetail() {
        String token = "";
        String userId = "";
        if (null != UserManager.getInstance().getUser()) {
            token = UserManager.getInstance().getUser().getToken();
            userId = UserManager.getInstance().getUser().getUserId();
        }
        mIsLoading = true;
        Map<String, Object> param = new HashMap<>();
        param.put("siteNumber", Constances.SITE_ID);
        param.put("nodeId", accointId);
        param.put("userId", userId);
        param.put("token", token);
        param.put("type", 4);

        showProgress("正在加载...");
        NetUtils.getNetAdapter().getAccountInfo(getOwnerName(), param, new AbsNetCallBack<AccountBean>(String.class) {
            @Override
            public void onSuc(AccountBean account) {
                if (null != account) {
                    mAccountDetailBean = account;
                    initDetail(mAccountDetailBean);
                    initTab();
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast("获取互动详情失败");
            }

            @Override
            public void onEnd() {
                closeProgress();
                mIsLoading = false;
            }
        });


    }

    /**
     * 初始化公众号信息
     *
     * @param detail
     */
    private void initDetail(AccountBean detail) {
        GlideUtil.getCircleGlid(this, detail.getFollowedSmallImage(), true).diskCacheStrategy(DiskCacheStrategy.NONE).transform(circleTransform).into(accountAvatar);
        accountTopName.setText(detail.getFollowedName());
        if (detail.getFollowedStatus() == 1) {
            accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
        } else {
            accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
        }
        accountPublishNum.setText("" + detail.getInfoAmount());
        accountAttentionNum.setText("" + detail.getFollowAmount());
        accountFansNum.setText("" + detail.getFollowedAmount());
        accountBePraisedNum.setText("" + detail.getBePrarisedNumber());
//        accountAutInfo.setText("" + detail.getAutIntro());
//        accountAddress.setText("" + detail.getLocation());
        accountIntro.setText(detail.getFollowedMetaDescription());


    }

    /**
     * 加载公众号新闻tab
     */
    private void initTab() {
        List<AccountTabBean> tabList = new ArrayList<>();
        tabList.add(new AccountTabBean(accointId, 1, "全部", AccountDetailPagerAdapter.TYPE_ALL_NEWS));
        tabList.add(new AccountTabBean(accointId, 2, "视频", AccountDetailPagerAdapter.TYPE_BAOLIAO_VIDOE));
        tabList.add(new AccountTabBean(accointId, 3, "文章", AccountDetailPagerAdapter.TYPE_NEWS_ITEM));
        if (adapter == null) {
            adapter = new AccountDetailPagerAdapter(getSupportFragmentManager(), tabList);
            accountContentVp.setAdapter(adapter);
            accountContentVp.setOffscreenPageLimit(1);
            accountTabLay.setViewPager(accountContentVp);
            accountTabLay.setChangeSize(true);
        } else {
            adapter.setData(tabList);
        }
        adapter.notifyDataSetChanged();
        accountTabLay.setCurrentTab(0);
        accountTabLay.setTabSpaceEqual(true);
        accountTabLay.setTabPaddingPx(getResources().getDimension(R.dimen.tab_home_padding));
        accountTabLay.setOnTabSelectListener(this);
    }


    @Override
    public void onTabSelect(int position) {
        currentIndex = position;
//        initFragmentRefreshStatus();
    }

    @Override
    public void onTabReselect(int position) {

    }

    @Override
    public void onTabScrollTo(int position) {

    }

    @OnClick(value = {R.id.account_detail_back, R.id.account_subscribe})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.account_detail_back:
                onBackPressed();
                break;
            case R.id.account_subscribe:
                //TODO 关注、取消关注
                if (null != UserManager.getInstance().getUser()) {
                    setResult(RESULT_OK);
                    toAttentionClick(mAccountDetailBean.getFollowedStatus());
                } else {
                    toLogin();
                }
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                setResult(RESULT_OK);
            }
        }
    }

    /**
     * 根据滑动位移设置列表是否可以下拉刷新
     */
    private void initFragmentRefreshStatus() {
        if (null != adapter) {
            AccountDetailNewsFragment fragment = (AccountDetailNewsFragment) adapter.getFragmentByPos(currentIndex);
            if (currentOffset == 0) {
                fragment.setRefreshLayoutRefreshEnable(true);
            } else {
                fragment.setRefreshLayoutRefreshEnable(false);
            }
        }
    }

    /**
     * 处理 关注或取消关注
     *
     * @param isAttention
     */
    private void toAttentionClick(int isAttention) {
        if (isAttention == 1) {
            toUnAttentionAccount(mAccountDetailBean.getFollowedId(), new OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {

                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {
                    mAccountDetailBean.setFollowedStatus(0);
                    accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
                }
            });
        } else {
            toAttentionAccount(mAccountDetailBean.getFollowedId(), new OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {
                    mAccountDetailBean.setFollowedStatus(1);
                    accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {

                }
            });
        }
    }


}
